import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WatchRecord } from './watchRecord.entity';
import { WatchRecordIc } from '../watchRecordIc/watchRecordIc.entity';
import DataBase from 'src/config/database';
import { Video } from '../video/video.entity';
import { WorkTypeEnum } from '../watchRecordIc/watchRecordIc.enum';
import utils from 'src/common/utils';


@Injectable()
export class WatchRecordService {
  constructor(
    @InjectRepository(WatchRecord)
    private repository: Repository<WatchRecord>,
    @InjectRepository(WatchRecordIc)
    private watchRecordIcRepository: Repository<WatchRecordIc>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
  ) {}

  findAll(): Promise<WatchRecord[]> {
    return this.repository.find();
  }

  findOne(id: any): Promise<WatchRecord> {
    return this.repository.findOne(id);
  }

  findByVideoIdAndWxUser(video_id, wx_user): Promise<WatchRecord> {
    return this.repository.findOne({where:{video_id, wx_user}})
  }

  async remove(id: number): Promise<void> {
    await this.repository.delete(id);
  }

  async create(cats: WatchRecord, work_type?: string): Promise<void> {
    //查询视频所属网红
    let findVideo = await this.videoRepository.findOne({where:{id: cats.video_id}})
    if(!findVideo){
      throw new Error('视频不存在')
    }
    await this.repository.save(cats);
    if(findVideo.ic_group){
      let watchRecordIc = new WatchRecordIc()
      watchRecordIc.wx_user = cats.wx_user
      watchRecordIc.create_time = new Date()
      watchRecordIc.ic_group = findVideo.ic_group
      if(work_type){
        watchRecordIc.work_type = utils.getMainWorkType(work_type)
      }
      await this.watchRecordIcRepository.save(watchRecordIc)
    }
  }
}
